package com.xbongbong.pro.statistic.service.result;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.service.toolbox.statistic.util.ChartResultUtil;
import com.xbongbong.pro.statistic.constant.ChartI18Constant;
import com.xbongbong.pro.statistic.enums.NumFormatEnum;
import com.xbongbong.pro.statistic.enums.SystemCodeEnum;
import com.xbongbong.pro.statistic.enums.ValueTypeEnum;
import com.xbongbong.pro.statistic.pojo.vo.ProductInfoVO;
import com.xbongbong.pro.statistic.result.pojo.ChartResultPojo;
import com.xbongbong.pro.statistic.result.pojo.ElasticAggsPojo;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartResultDetailVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultDataTableVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultTableVO;
import com.xbongbong.pro.statistic.through.pojo.dto.ThroughDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.PageConstant;
import com.xbongbong.saas.domain.entity.ProductCategoryEntity;
import com.xbongbong.saas.domain.entity.PurchaseProductEntity;
import com.xbongbong.saas.domain.entity.SupplierUserEntity;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.model.ProductCategoryModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.SpecificationModel;
import com.xbongbong.saas.service.toolbox.help.ProductHelp;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 采购合同相关统计
 *
 * @author 徐俊杰
 * @version v1.0
 * @date 2019/3/13 9:33
 * @since v1.0
 */
@Service
public class JxcPurchaseResult extends ChartResultParentService implements ChartResultSystem {
    @Resource
    private ProductHelp productHelp;
    @Resource
    private ProductCategoryModel productCategoryModel;
    @Resource
    private SpecificationModel specificationModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;

    @Override
    public Object getTarget(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        SystemCodeEnum systemCodeEnum = chartResultPojo.getSystemCodeEnum();
        switch (systemCodeEnum) {
            case PURCHASE_COUNT_HOME:
                return purchaseCountHome(chartResultPojo, chartResultDetailVO);
            case PURCHASE_AMOUNT_HOME:
                return purchaseAmountHome(chartResultPojo, chartResultDetailVO);
            case PURCHASE_TABLE_CHART:
                return purchaseTableChart(chartResultPojo, chartResultDetailVO);
            case PURCHASE_SUPPLIER_TABLE_CHART:
                return purchaseSupplierTableChart(chartResultPojo, chartResultDetailVO);
            default:
                break;
        }
        return null;
    }

    @Override
    public Object getValueTarget(ChartResultPojo chartResultPojo) throws XbbException {
        SystemCodeEnum systemCodeEnum = chartResultPojo.getSystemCodeEnum();
        switch (systemCodeEnum) {
            case PURCHASE_COUNT_BOARD:
                return purchaseCountBoard(chartResultPojo);
            case PURCHASE_AMOUNT_BOARD:
                return purchaseAmountBoard(chartResultPojo);
            default:
                break;
        }
        return null;
    }

    /**
     * 采购合同数（简报看板）
     *
     * @param chartResultPojo 内部存系统指标统计时需要的参数
     * @return java.lang.String
     * @author 徐俊杰
     * @date 2019/3/13 13:39
     * @since v1.0
     */
    public String purchaseCountBoard(ChartResultPojo chartResultPojo) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = chartQueryHelp.purchaseQuery(chartResultPojo);
        ElasticAggsPojo elasticAggsPojo = esHelper.elasticAggs(IndexTypeEnum.IDX_SAAS_PURCHASE, boolQueryBuilder, null);
        return elasticAggsPojo.getTotal();
    }

    /**
     * 采购金额（简报看板）
     *
     * @param chartResultPojo 内部存系统指标统计时需要的参数
     * @return java.lang.String
     * @author 徐俊杰
     * @date 2019/3/13 13:38
     * @since v1.0
     */
    public String purchaseAmountBoard(ChartResultPojo chartResultPojo) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = chartQueryHelp.purchaseQuery(chartResultPojo);
        String sumField = PurchaseEnum.getEsAttr4Keyword(PurchaseEnum.TOTAL_MONEY);
        double amount = systemChartHelp.getDouble4Total(IndexTypeEnum.IDX_SAAS_PURCHASE, boolQueryBuilder, sumField);
        return ChartResultUtil.formatValue2Double(false, ValueTypeEnum.VALUE_MONEY, chartResultPojo.isThousandSwitch(), amount, NumFormatEnum.getByCode(chartResultPojo.getNumFormat()), chartResultPojo.getNumFormatFlag());
    }

    /**
     * 采购合同数（首页）
     *
     * @param chartResultPojo 内部存系统指标统计时需要的参数
     * @param chartResultDetailVO 结果
     * @return java.lang.Object
     * @throws XbbException
     * @author 徐俊杰
     * @date 2019/3/15 21:01
     * @since v1.0
     */
    public Object purchaseCountHome(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        ElasticAggsPojo elasticAggsPojo = purchaseCount2ElasticAggsPojo(chartResultPojo, ValueTypeEnum.VALUE_TYPE);
        ThroughDTO throughDTO = new ThroughDTO(chartResultPojo, chartResultPojo.getSystemCodeEnum());
        //是否画入表格内 0否1是
        Integer tableFlag = 0;
        String legend = null;
        String unit = null;
        Boolean totalFlag = false;
        String valueTitle = null;
        return systemChartHelp.packageResult4One(elasticAggsPojo, chartResultPojo, chartResultDetailVO, throughDTO, tableFlag, legend, unit, totalFlag, valueTitle);
    }

    /**
     * 采购金额（首页）
     *
     * @param chartResultPojo 内部存系统指标统计时需要的参数
     * @param chartResultDetailVO 结果
     * @return java.lang.Object
     * @throws XbbException
     * @author 徐俊杰
     * @date 2019/3/15 21:03
     * @since v1.0
     */
    public Object purchaseAmountHome(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        ElasticAggsPojo elasticAggsPojo = purchaseAmount2ElasticAggsPojo(chartResultPojo, ValueTypeEnum.ARRAY_TYPE, PurchaseEnum.TOTAL_MONEY);
        ThroughDTO throughDTO = new ThroughDTO(chartResultPojo, chartResultPojo.getSystemCodeEnum());
        //是否画入表格内 0否1是
        Integer tableFlag = 1;
        String legend = SystemCodeEnum.PURCHASE_AMOUNT_HOME.getName();
        String unit = NumFormatEnum.getByCode(chartResultPojo.getNumFormat()).getUnit();
        Boolean totalFlag = true;
        String valueTitle = SystemCodeEnum.PURCHASE_AMOUNT_HOME.getName();
        return systemChartHelp.packageResult4One(elasticAggsPojo, chartResultPojo, chartResultDetailVO, throughDTO, tableFlag, legend, unit, totalFlag, valueTitle);
    }

    /**
     * 采购汇总表
     * @param chartResultPojo
     * @param chartResultDetailVO
     * @return com.xbongbong.pro.statistic.result.pojo.vo.ChartResultDetailVO 
     * @throws XbbException
     * @author zcp
     * @date 2019/4/9 21:53
     * @since v1.0
     * @version v1.0
     */
    public ChartResultDetailVO purchaseTableChart(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        ChartResultUtil.formatPage(chartResultPojo, PageConstant.DEFAULT_PAGE_SIZE_SMALL);
        Integer page = chartResultPojo.getPage();
        Integer pageSize = chartResultPojo.getPageSize();
        String corpid = chartResultPojo.getCorpid();
        List<PaasFormDataEntityExt> purchaseList = formHelp.getPurchaseList(chartResultPojo, Collections.singletonList(FieldTypeEnum.DATAID.getAlias()));
        Set<Long> purchaseIdIn = new HashSet<>();
        for (PaasFormDataEntityExt entityExt : purchaseList) {
            purchaseIdIn.add(entityExt.getDataId());
        }
        List<PurchaseProductEntity> purchaseProductList = productHelp.getPurchaseProductList(corpid, purchaseIdIn);
        //产品id--采购产品实体list
        Map<Long, List<PurchaseProductEntity>> purchaseProductMap = new HashMap<>(purchaseProductList.size());
        Set<Long> productIdIn = new HashSet<>();
        productIdIn.add(-1L);
        for (PurchaseProductEntity purchaseProduct : purchaseProductList) {
            Long productId = purchaseProduct.getProductId();
            productIdIn.add(productId);
            List<PurchaseProductEntity> list = purchaseProductMap.get(productId);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(purchaseProduct);
            purchaseProductMap.put(productId, list);
        }
        //限制产品ids
        BoolQueryBuilder boolQueryBuilder = chartQueryHelp.boolQueryBuilder4BaseByIds(corpid, DelEnum.NORMAL.getDel(), productIdIn, IndexTypeEnum.IDX_SAAS_PRODUCT);
        //分页查询
        XbbAggregatedPage<ProductInfoVO> esEntities = esHelper.findByPage(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, ProductInfoVO.class, null, page, pageSize, null);
        List<ProductInfoVO> productInfoVoList = new ArrayList<>();
        int rowCounts = 0;
        if (esEntities != null) {
            productInfoVoList = esEntities.getContent();
            rowCounts = (int) esEntities.getTotalElements();
        }
        PageHelper pageHelper = PageHelperUtil.initPageHelper(rowCounts, page, pageSize, PageConstant.DEFAULT_PAGE_SIZE_SMALL);
        //封装采购汇总报表信息
        List<List<ResultDataTableVO>> tableData = formatPurchaseTableData(corpid, productInfoVoList, purchaseProductMap, chartResultPojo);
        ResultTableVO table = new ResultTableVO();
        List<String> title = Arrays.asList(String.format(I18nMessageUtil.getMessage(ChartI18Constant.PURCHASE_TABLE_CHART_TITLE), chartResultPojo.getUnit()).split(","));
        table.setTitle(systemChartHelp.titleNumRight(title));
        table.setTableName(chartResultPojo.getChartEntity().getName());
        table.setData(tableData);
        table.setPageHelper(pageHelper);
        chartResultDetailVO.setTable(table);
        return chartResultDetailVO;
    }

    /**
     * 供应商往来汇总表
     * @param chartResultPojo
     * @param chartResultDetailVO
     * @return com.xbongbong.pro.statistic.result.pojo.vo.ChartResultDetailVO 
     * @throws XbbException
     * @author zcp
     * @date 2019/4/10 13:56
     * @since v1.0
     * @version v1.0
     */
    public ChartResultDetailVO purchaseSupplierTableChart(ChartResultPojo chartResultPojo, ChartResultDetailVO chartResultDetailVO) throws XbbException {
        ChartResultUtil.formatPage(chartResultPojo, PageConstant.DEFAULT_PAGE_SIZE_SMALL);
        Integer page = chartResultPojo.getPage();
        Integer pageSize = chartResultPojo.getPageSize();
        List<String> fieldList = Arrays.asList(PurchaseEnum.getAttrConnectData(PurchaseEnum.SUPPLIER_ID), PurchaseEnum.getAttrConnectData(PurchaseEnum.TOTAL_MONEY));
        List<PaasFormDataEntityExt> purchaseList = formHelp.getPurchaseList(chartResultPojo, fieldList);
        fieldList = Arrays.asList(ReturnedPurchaseEnum.getAttrConnectData(ReturnedPurchaseEnum.SUPPLIER_ID), ReturnedPurchaseEnum.getAttrConnectData(ReturnedPurchaseEnum.TOTAL_MONEY));
        List<PaasFormDataEntityExt> returnedPurchaseList = formHelp.getReturnedPurchaseList(chartResultPojo, fieldList);
        //采购合同、采购退货关联的所有供应商ids
        Set<Long> supplierIdIn = new HashSet<>();
        //供应商id--Purchase的数量
        Map<Long, Integer> idCountPurchaseMap = new HashMap<>(purchaseList.size());
        //供应商id--Purchase的金额
        Map<Long, Double> idAmountPurchaseMap = new HashMap<>(purchaseList.size());
        //供应商id--ReturnedPurchase的数量
        Map<Long, Integer> idCountReturnedPurchaseMap = new HashMap<>(returnedPurchaseList.size());
        //供应商id--ReturnedPurchase的金额
        Map<Long, Double> idAmountReturnedPurchaseMap = new HashMap<>(returnedPurchaseList.size());
        //-------------采购合同
        String supplierIdAttr = PurchaseEnum.SUPPLIER_ID.getAttr();
        String totalMoneyAttr = PurchaseEnum.TOTAL_MONEY.getAttr();
        formatSupplierCountMoney(purchaseList, supplierIdIn, idCountPurchaseMap, idAmountPurchaseMap, supplierIdAttr, totalMoneyAttr);
        //-------------采购退货
        supplierIdAttr = ReturnedPurchaseEnum.SUPPLIER_ID.getAttr();
        totalMoneyAttr = ReturnedPurchaseEnum.TOTAL_MONEY.getAttr();
        formatSupplierCountMoney(returnedPurchaseList, supplierIdIn, idCountReturnedPurchaseMap, idAmountReturnedPurchaseMap, supplierIdAttr, totalMoneyAttr);
        //限制供应商ids
        BoolQueryBuilder boolQueryBuilder = chartQueryHelp.boolQueryBuilder4BaseByIds(chartResultPojo.getCorpid(), DelEnum.NORMAL.getDel(), supplierIdIn, IndexTypeEnum.IDX_SAAS_SUPPLIER);
        XbbAggregatedPage<PaasFormDataEntityExt> esEntities = esHelper.findByPage(IndexTypeEnum.IDX_SAAS_SUPPLIER, boolQueryBuilder, PaasFormDataEntityExt.class, null, page, pageSize, null);
        List<PaasFormDataEntityExt> supplierList = new ArrayList<>();
        List<PaasFormDataEntity> supplierUserList = new ArrayList<>();
        int rowCounts = 0;
        if (esEntities != null) {
            supplierList = esEntities.getContent();
            rowCounts = (int) esEntities.getTotalElements();
            supplierUserList = formHelp.getUserTeamListByIds(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM, chartResultPojo.getCorpid(), supplierIdIn, BasicConstant.MAIN_USER, PaasFormDataEntity.class);
        }
        List<SupplierUserEntity> userTeamEntities = (List<SupplierUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM, supplierUserList);
        //supplierId--负责人名称（后续会改成多个负责人，因此要考虑到）
        Map<Long, String> supplierNameMap = commonHelp.getUserTeamNameMap(userTeamEntities);
        String nameAttr = SupplierEnum.SUPPLIER_NAME.getAttr();
        List<List<ResultDataTableVO>> tableData = new ArrayList<>();
        for (PaasFormDataEntityExt entityExt : supplierList) {
            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            Long supplierId = entityExt.getDataId();
            // 采购合同数
            Integer purchaseCount = idCountPurchaseMap.get(supplierId);
            // 采购金额
            Double purchaseAmount = idAmountPurchaseMap.get(supplierId);
            // 采购退货单数
            Integer returnPurchaseCount = idCountReturnedPurchaseMap.get(supplierId);
            // 采购退货金额
            Double returnPurchaseAmount = idAmountReturnedPurchaseMap.get(supplierId);
            String purchaseCountStr = (purchaseCount == null) ? "0" : String.valueOf(purchaseCount);
            String returnPurchaseCountStr = (returnPurchaseCount == null) ? "0" : String.valueOf(returnPurchaseCount);
            purchaseAmount = (purchaseAmount == null) ? Double.valueOf(0) : purchaseAmount;
            returnPurchaseAmount = (returnPurchaseAmount == null) ? Double.valueOf(0) : returnPurchaseAmount;
            String managerName = supplierNameMap.get(supplierId);
            if (StringUtil.isEmpty(managerName)) {
                managerName = "";
            }
            List<ResultDataTableVO> voList = new ArrayList<>();
            ResultDataTableVO resultDataTableVo = new ResultDataTableVO(data.getString(nameAttr), null);
            //把主键id置入，方便检查数据
            resultDataTableVo.setDataId(entityExt.getDataId());
            voList.add(resultDataTableVo);
            voList.add(new ResultDataTableVO(managerName, null));
            voList.add(new ResultDataTableVO(purchaseCountStr, null));
            voList.add(new ResultDataTableVO(returnPurchaseCountStr, null));
            voList.add(new ResultDataTableVO(StringUtil.formatDouble(purchaseAmount), null));
            voList.add(new ResultDataTableVO(StringUtil.formatDouble(returnPurchaseAmount), null));
            voList.add(new ResultDataTableVO(StringUtil.formatDouble(purchaseAmount - returnPurchaseAmount), null));
            tableData.add(voList);
        }
        PageHelper pageHelper = PageHelperUtil.initPageHelper(rowCounts, page, pageSize, PageConstant.DEFAULT_PAGE_SIZE_SMALL);
        ResultTableVO table = new ResultTableVO();
        List<String> title = Arrays.asList(I18nMessageUtil.getMessage(ChartI18Constant.PURCHASE_SUPPLIER_TABLE_CHART_TITLE).split(","));
        table.setTitle(systemChartHelp.titleNumRight(title));
        table.setTableName(chartResultPojo.getChartEntity().getName());
        table.setData(tableData);
        table.setPageHelper(pageHelper);
        chartResultDetailVO.setTable(table);
        return chartResultDetailVO;
    }

    /**
     * 获取采购合同数的ElasticAggsPojo
     *
     * @param chartResultPojo 内部存系统指标统计时需要的参数
     * @param valueTypeEnum 值的类型
     * @return com.xbongbong.paas.elasticsearch.pojo.ElasticAggsPojo
     * @author 徐俊杰
     * @date 2019/3/13 11:33
     * @since v1.0
     */
    private ElasticAggsPojo purchaseCount2ElasticAggsPojo(ChartResultPojo chartResultPojo, ValueTypeEnum valueTypeEnum) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = chartQueryHelp.purchaseQuery(chartResultPojo);
        String fieldTime = PurchaseEnum.getEsAttr4Keyword(PurchaseEnum.SIGN_TIME);
        return systemChartHelp.getCount4Agg(chartResultPojo, valueTypeEnum, IndexTypeEnum.IDX_SAAS_PURCHASE, boolQueryBuilder, fieldTime);
    }

    /**
     * 获取采购金额的ElasticAggsPojo
     *
     * @param chartResultPojo 内部存系统指标统计时需要的参数
     * @param valueTypeEnum 值的类型
     * @param attrEnum 求和字段
     * @return com.xbongbong.paas.elasticsearch.pojo.ElasticAggsPojo
     * @author 徐俊杰
     * @date 2019/3/13 11:34
     * @since v1.0
     */
    private ElasticAggsPojo purchaseAmount2ElasticAggsPojo(ChartResultPojo chartResultPojo, ValueTypeEnum valueTypeEnum, PurchaseEnum attrEnum) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = chartQueryHelp.purchaseQuery(chartResultPojo);
        String sumField = PurchaseEnum.getEsAttr4Keyword(attrEnum);
        String fieldTime = PurchaseEnum.getEsAttr4Keyword(PurchaseEnum.SIGN_TIME);
        chartResultPojo.setValueTypeEnum(ValueTypeEnum.VALUE_MONEY);
        return systemChartHelp.getDouble4Agg(chartResultPojo, valueTypeEnum, IndexTypeEnum.IDX_SAAS_PURCHASE, boolQueryBuilder, fieldTime, sumField);
    }
    
    /**
     * 封装采购汇总报表的信息
     * @param corpid 公司id
     * @param productInfoVoList 产品list
     * @param purchaseProductMap 产品id--采购产品实体list
     * @param chartResultPojo
     * @return java.util.List<java.util.List<com.xbongbong.pro.statistic.result.pojo.vo.ResultDataTableVO>> 
     * @throws XbbException
     * @author zcp
     * @date 2019/4/9 21:49
     * @since v1.0
     * @version v1.0
     */
    private List<List<ResultDataTableVO>> formatPurchaseTableData(String corpid, List<ProductInfoVO> productInfoVoList, Map<Long, List<PurchaseProductEntity>> purchaseProductMap, ChartResultPojo chartResultPojo) throws XbbException {
        Set<Long> parentIdIn = new HashSet<>();
        Set<Long> categoryIdIn = new HashSet<>();
        String categoryIdAttr = ProductEnum.CATEGORY_ID.getAttr();
        String parentIdAttr = ProductEnum.PARENT_ID.getAttr();
        Integer numFormat = chartResultPojo.getNumFormat();
        NumFormatEnum numFormatEnum = NumFormatEnum.getByCode(numFormat);
        for (ProductInfoVO product : productInfoVoList) {
            JSONObject data = JsonHelperUtil.getJSONObject(product.getData());
            categoryIdIn.add(data.getLong(categoryIdAttr));
            parentIdIn.add(data.getLong(parentIdAttr));
        }
        //父级产品id--产品编号map
        Map<Long, String> parentIdNoMap = formHelp.getParentIdNoMap(corpid, parentIdIn);
        //分类id--分类信息
        Map<Long, ProductCategoryEntity> categoryMap = productCategoryModel.getProductCategoryMapByIdIn(corpid, categoryIdIn);

        String nameAttr = ProductEnum.NAME.getAttr();
        String specificationAttr = ProductEnum.SPECIFICATION_LINK_TEXT.getAttr();
        Map<String, String> productUnitItemMap = formHelp.getProductUnitItemMap(corpid);
        List<List<ResultDataTableVO>> tableData = new ArrayList<>();
        for (ProductInfoVO entityExt : productInfoVoList) {
            JSONObject data = JsonHelperUtil.getJSONObject(entityExt.getData());
            Long categoryId = data.getLongValue(categoryIdAttr);
            ProductCategoryEntity category = categoryMap.get(categoryId);
            String categoryName = (category == null) ? "" : category.getName();
            String unit = productUnitItemMap.getOrDefault(entityExt.getData().getString(ProductEnum.UNIT.getAttr()), "");
            double totalCount = 0d;
            double totalAmount = 0d;
            List<PurchaseProductEntity> list = purchaseProductMap.get(entityExt.getId());
            for (PurchaseProductEntity purchaseProductEntity : list) {
                double count = purchaseProductEntity.getProductNum();
                double price = purchaseProductEntity.getProductPrice();
                double amount = count * price;
                totalAmount += amount;
                totalCount += count;
            }
            List<ResultDataTableVO> voList = new ArrayList<>();
            ResultDataTableVO noVo = new ResultDataTableVO(formHelp.getProductNo(parentIdNoMap, data), null);
            //把主键id置入，方便检查数据
            noVo.setDataId(entityExt.getDataId());
            voList.add(noVo);
            voList.add(new ResultDataTableVO(data.getString(nameAttr), null));
            String specification = specificationModel.joinSpecification(data.getString(specificationAttr));
            voList.add(new ResultDataTableVO(specification, null));
            voList.add(new ResultDataTableVO(categoryName, null));
            voList.add(new ResultDataTableVO(unit, null));
            voList.add(new ResultDataTableVO(StringUtil.formatDouble(totalCount), null));
            voList.add(new ResultDataTableVO(ChartResultUtil.formatVal2Thousands(BigDecimal.valueOf(totalAmount), numFormatEnum), null));
            tableData.add(voList);
        }
        return tableData;
    }

    /**
     * 封装采购合同或采购退货的数量、金额，及塞入供应商ids
     * @param list 采购合同，或采购退货的list
     * @param supplierIdIn 供应商ids
     * @param idCountPurchaseMap 供应商id--Purchase的数量
     * @param idAmountPurchaseMap 供应商id--Purchase的金额
     * @param supplierIdAttr 供应商id的英文字段名
     * @param totalMoneyAttr 金额的英文字段名
     * @author zcp
     * @date 2019/4/10 13:53
     * @since v1.0
     * @version v1.0
     */
    private void formatSupplierCountMoney(List<PaasFormDataEntityExt> list, Set<Long> supplierIdIn, Map<Long, Integer> idCountPurchaseMap, Map<Long, Double> idAmountPurchaseMap, String supplierIdAttr, String totalMoneyAttr) {
        for (PaasFormDataEntityExt entity : list) {
            JSONObject data = JsonHelperUtil.getJSONObject(entity.getData());
            //供应商id
            Long supplierId = data.getLong(supplierIdAttr);
            if (supplierId == null) {
                continue;
            }
            //采购或采购退货金额
            Double totalMoney = data.getDoubleValue(totalMoneyAttr);
            supplierIdIn.add(supplierId);
            Integer count = idCountPurchaseMap.get(supplierId);
            Double amount = idAmountPurchaseMap.get(supplierId);
            count = (count == null) ? 1 : count + 1;
            amount = (amount == null) ? totalMoney : amount + totalMoney;
            idCountPurchaseMap.put(supplierId, count);
            idAmountPurchaseMap.put(supplierId, amount);
        }
    }
}
